import store from '../store/store'

import util from "./util"
const send_string = false

export function openBluetoothAdapter() {
	uni.openBluetoothAdapter({
		success: res => {
			console.log('openBluetoothAdapter success', res);
			startBluetoothDevicesDiscovery();
		},
		fail: res => {
			console.log(res);
			if (res.errCode === 10001) {
				uni.showToast({
					title: '请打开蓝牙',
					icon: 'none'
				});
				uni.onBluetoothAdapterStateChange(res => {
					console.log('onBluetoothAdapterStateChange', res);
					if (res.available) {
						startBluetoothDevicesDiscovery();
					}
				});
			}
		}
	});
}

function stopBluetoothDevicesDiscovery() {
	uni.stopBluetoothDevicesDiscovery();
}
export function closeBluetoothAdapter() {
	uni.closeBluetoothAdapter({
		success(res) {
			console.log(res)
			openBluetoothAdapter()
		},
		fail(res) {
			console.log(res, 'err')
			openBluetoothAdapter()
		}
	})
}

//蓝牙搜索
function startBluetoothDevicesDiscovery() {
	uni.startBluetoothDevicesDiscovery({
		allowDuplicatesKey: true,
		success: res => {
			onBluetoothDeviceFound();
			setTimeout(()=>{
				stopBluetoothDevicesDiscovery()
			},30000)
		}
	});
}
//监听设备
function onBluetoothDeviceFound() {
	uni.onBluetoothDeviceFound(res => {
		res.devices.forEach(device => {
			if (device.deviceId == store.state.device.deviceId) {
				createBLEConnection();
				stopBluetoothDevicesDiscovery()
			} else {
				console.log(device)
			}
		});
	});
}

function createBLEConnection() {
	const deviceId = store.state.device.deviceId;
	uni.createBLEConnection({
		deviceId,
		success: res => {
			// store.commit('setConnect', true)
			console.log('createBLEConnection11', res);
			//隐藏加载框
			getBLEDeviceServices();
		},
		complete(res) {
			console.log('createBLEConnection22', res);
		}
	});
}
//获取蓝牙设备服务
function getBLEDeviceServices() {
	const deviceId = store.state.deviceId;
	uni.getBLEDeviceServices({
		deviceId,
		success: res => {
			console.log(res);
			for (let i = 0; i < res.services.length; i++) {
				if (res.services[i].isPrimary) {
					store.commit('setServiceId', res.services[i].uuid)
					getBLEDeviceCharacteristics();
					return;
				}
			}
		}
	});
}

//获取蓝牙特征值
function getBLEDeviceCharacteristics() {
	const deviceId = store.state.deviceId
	const serviceId = store.state.serviceId
	uni.getBLEDeviceCharacteristics({
		deviceId,
		serviceId,
		success: res => {
			console.log('getBLEDeviceCharacteristics success', res.characteristics);
			for (let i = 0; i < res.characteristics.length; i++) {
				let item = res.characteristics[i];

				if (item.properties.read) {
					uni.readBLECharacteristicValue({
						deviceId,
						serviceId,
						characteristicId: item.uuid
					});
				}
				if (item.properties.write) {
					store.commit('setCharacteristicId', item.uuid)
				}
				if (item.properties.notify || item.properties.indicate) {
					uni.notifyBLECharacteristicValueChange({
						deviceId,
						serviceId,
						characteristicId: item.uuid,
						state: true
					});
				}
				store.commit('setConnect', true)
			}
		},
		fail(res) {
			console.error('getBLEDeviceCharacteristics', res);
		}
	});
	uni.onBLECharacteristicValueChange(characteristic => {
		if (!store.state.connect) {
			return
		}
		var result = characteristic.value;
		var hex = util.buf2hex(result);
		//自己的操作
		console.log('设备返回来的值1', hex);
		console.log('最终转回来的值2', util.hexStrToStr(hex))
		setValue(util.hexStrToStr(hex))
	});
	uni.onBLEConnectionStateChange(res => {
		// 该方法回调中可以用于处理连接意外断开等异常情况
		console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`);
		const connect = res.connected;
		store.commit('setConnect', connect)
		if (connect) {

			openBluetoothAdapter();
		}

	});
}


/* 发送输入框的值 */
export function SendTap(send_value) {
	var write_array = [];
	var charCodeAt = [];
	var value_ascii = "";
	var recv_value_ascii = "";
	var string_value = "";
	var recve_value = "";
	var value_initial_1 = send_value; //拿到输入框的值
	console.log('输入框中的值', value_initial_1);
	/* 判断是否存在空格 */
	// if (value_initial_1.indexOf(' ') > 0) {
	// 	var value_initial = that.splitStr(value_initial_1, ' '); //存在空格时
	// 	console.log('删除掉空格', value_initial);
	// } else {
	// 	var value_initial = value_initial_1; //不存在空格时
	// }
	var value_initial = value_initial_1; //不存在空格时


	/* 判断字节是否超过20字节 */
	if (value_initial.length > 20) { //当字节超过20的时候，采用分段发送
		if (send_string == true) { //选择16进制发送时
			var value_initial_exceed = value_initial; //将输入框的值取过来，方便循环
			var value_initial_average = Math.ceil(value_initial_exceed.length /
				20); //将value_initial_exceed的长度除以20，余数再向上取一，确定循环几次
			console.log('需要循环的次数', value_initial_average);
			for (var i = 0; i < value_initial_average; i++) {
				if (value_initial_exceed.length > 20) {
					var value_initial_send = value_initial_exceed.slice(0, 20); //截取前20个字节
					console.log('截取到的值', value_initial_send);
					value_initial_exceed = value_initial_exceed.substring(
						20); //value_initial_exceed替换为取掉前20字节后的数据
					write_array.push(value_initial_send); //将所有截取的值放在一个数组
				} else {
					write_array.push(value_initial_exceed);
				}
			}
			console.log('write_array数组', write_array);
			write_array.map(function(val, index) {
				setTimeout(function() {
					var value_set = val;
					console.log('value_set', value_set);
					var write_function = write(value_set); //调用数据发送函数
				}, index * 100)
			});
			// /* 发送的值的字节 */
			// var send_number_1 = that.send_number + value_initial.length / 2;
			// var send_number = Math.floor(send_number_1);

		} else { //选择Ascii码发送

			/* 当选择以Ascii字符发送的时候 */
			var value_split = value_initial.split(''); //将字符一个一个分开
			console.log('value_split', value_split);
			for (var i = 0; i < value_split.length; i++) {
				value_ascii = value_ascii + value_split[i].charCodeAt().toString(16); //转为Ascii字符后连接起
			}
			var Ascii_value = value_ascii;
			console.log('转为Ascii码值', Ascii_value);
			console.log('Ascii_value的长度', Ascii_value.length)
			var Ascii_send_time = Math.ceil(Ascii_value.length / 20);
			console.log('Ascii发送的次数', Ascii_send_time);
			for (var i = 0; i < Ascii_send_time; i++) {
				if (Ascii_value.length > 20) {
					var value = Ascii_value.slice(0, 20);
					console.log('截取到的值', value);
					Ascii_value = Ascii_value.substring(20);
					console.log('此时剩下的Ascii_value', Ascii_value);
					write_array.push(value); //放在数组里面
				} else {
					var value = Ascii_value;
					write_array.push(Ascii_value); //放在数组里面
				}
			}
			console.log('数组write_array', write_array);
			write_array.map(function(val, index) {
				setTimeout(function() {
					var value_set = val;
					console.log('value_set', value_set);
					var write_function = write(value_set); //调用数据发送函数
				}, index * 100)
			});


		}
	} else { //当字节不超过20的时候，直接发送
		/* 判断选择了Hex还是Ascii发送 */
		if (send_string == true) {
			/* 当选择了以Hex十六进制发送的时候 */
			var value = value_initial;
		} else {
			/* 当选择以Ascii字符发送的时候 */
			var value_split = value_initial.split(''); //将字符一个一个分开
			console.log('value_split', value_split);
			for (var i = 0; i < value_split.length; i++) {
				value_ascii = value_ascii + value_split[i].charCodeAt().toString(16); //转为Ascii字符后连接起
			}
			var value = value_ascii;
			console.log('转为Ascii码值', value);
		}
		var write_function = write(value); //调用数据发送函数

	}
}

function write(str) {

	var value = str;
	console.log('value', value);
	/* 将数值转为ArrayBuffer类型数据 */
	var typedArray = new Uint8Array(value.match(/[\da-f]{2}/gi).map(function(h) {
		return parseInt(h, 16)
	}));
	console.log('typedArray', typedArray)
	var buffer = typedArray.buffer;
	wx.writeBLECharacteristicValue({
		deviceId: store.state.deviceId,
		serviceId: store.state.serviceId,
		characteristicId: store.state.characteristicId,
		value: buffer,
		success: function(res) {
			console.log('数据发送成功', res);
		},
		fail: function(res) {
			stopBluetoothDevicesDiscovery()
			closeBluetoothAdapter()
			console.log('调用失败', store.state.characteristicId, res);
			/* 调用失败时，再次调用 */
			wx.writeBLECharacteristicValue({
				deviceId: store.state.deviceId,
				serviceId: store.state.serviceId,
				characteristicId: store.state.characteristicId,
				value: buffer,
				success: function(res) {
					console.log('第2次数据发送成功', res);
				},
				fail: function(res) {
					console.log('第2次调用失败', res);
					
					/* 调用失败时，再次调用 */
					wx.writeBLECharacteristicValue({
						deviceId: store.state.deviceId,
						serviceId: store.state.serviceId,
						characteristicId: store.state.characteristicId,
						value: buffer,
						success: function(res) {
							console.log('第3次数据发送成功', res);
						},
						fail: function(res) {
							console.log('第3次调用失败', res);
						}
					});
				}
			});
		}
	});
}

function format(str) {
	const arr = str.split('=')
	if (arr.length > 1) {
		return {
			code: arr[0].substring(4),
			value: arr[1]
		}
	}
	return {}
}
export function setValue(str) {
	if (!str) {
		return
	}
	const data = format(str)
	//温度
	if (data.code == 1001) {
		store.commit('setTemp', data.value)
	}
	//湿度
	else if (data.code == 1002) {
		store.commit('setHumidity', data.value)
	}
	//电池电压
	else if (data.code == 1003) {
		store.commit('setPower', data.value)
	}


}
